package top.wshape1.rpc.filter;

import lombok.extern.slf4j.Slf4j;
import top.wshape1.rpc.common.constant.AttachmentConstant;
import top.wshape1.rpc.common.exception.RpcException;
import top.wshape1.rpc.config.JJRpcConfig;
import top.wshape1.rpc.message.RpcMessage;
import top.wshape1.rpc.message.RpcRequest;

import java.util.Objects;

/**
 * @author Wshape1
 * @version 1.0
 * @description
 * @since 2024-02-15
 */

@Slf4j
public class ConsumerTokenFilter implements Filter {
    @Override
    public int getOrder() {
        return HIGHEST_PRECEDENCE;
    }

    @Override
    public boolean doFilter(RpcMessage message, FilterChain filterChain) throws RpcException {
        if (message instanceof RpcRequest) {
            message.getAttachments().putIfAbsent(AttachmentConstant.TOKEN, JJRpcConfig.CONFIG.getToken());
        } else {
            Object token = message.getAttachments().get(AttachmentConstant.TOKEN);
            if (!Objects.equals(JJRpcConfig.CONFIG.getToken(), token)) {
                log.debug("token is not match. msg: {}", message);
                return false;
            }
        }
        return filterChain.doFilter(message);
    }
}
